package com.doucat.support.component.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import com.doucat.support.dialog.AskDialog;
import com.doucat.support.dialog.TipDialog;
import com.doucat.support.model.inter.InterfaceView;
import com.doucat.support.thread.WorkersThread;
import com.tonly.doucatlibrary.R;

import java.util.List;

public class BaseActivity extends AppCompatActivity implements InterfaceView{
    protected String TAG=getClass().getSimpleName();
    public Context getContext(){
        return this;
    }
    protected void startActivity(Class c){
        Intent intent=new Intent(this,c);
        startActivity(intent);
    }
    protected void print(String log){
        Log.d(TAG,log);
    }
    public void startService(Context context, Intent intent){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    private TipDialog tipDialog;
    private AskDialog askDialog;
    private Toast toast;

    private Handler mainHandler;
    private WorkersThread threadPool;

    private FrameLayout baseContent;
    public ContentLoadingProgressBar progressLoading;
    private ViewGroup layoutEmpty;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);

        baseContent = findViewById(R.id.baseContent);
        progressLoading = findViewById(R.id.progressLoading);
        layoutEmpty=findViewById(R.id.layoutEmpty);
        /**
         * loadThread延迟初始化
         * 消息会阻塞，发了不执行
         *
         * mainHandler不能保证调用的地方是UI线程，也就不能保证getMainLooper
         */
        threadPool= WorkersThread.getInstance();
        mainHandler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                onGetMessage(msg);
            }
        };
        getWindow().setStatusBarColor(getColor(R.color.title));
    }

    public void setBaseFrameLayout(int layoutResID) {
//        super.setContentView(layoutResID);
        baseContent.removeAllViews();
        View.inflate(this, layoutResID, baseContent);
//        onContentChanged();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainHandler.removeCallbacksAndMessages(null);
        threadPool.shutdownNow();
        dismissLoading();
        dismissTip();
        dismissAsk();
    }
    /*****************************************多线程*******************************************/
    public void onGetMessage(Message msg){

    }

    /**
     * @param runnable
     */
    public void runOnThread(Runnable runnable){
        threadPool.execute(runnable);
    }

    /**
     * @param message
     */
    public void sendToMainThread(Message message){
        mainHandler.sendMessage(message);
    }

    /************************************************提示信息**********************************************/
    /**
     * 显示提示对话框
     */
    public void showTipDialog(String s) {
        showTipDialog(getSupportFragmentManager(),s,null,null);
    }

    public void showTipDialog(String s,String rightString, View.OnClickListener rightClick) {
        showTipDialog(getSupportFragmentManager(),s,rightString,rightClick);
    }

    public void showAsk(String title, String leftString, View.OnClickListener leftClick, String rightString, View.OnClickListener rightClick){
        showAsk(getSupportFragmentManager(),title,leftString,leftClick,rightString,rightClick);
    }

    /**
     * 显示提示对话框
     */
    private void showTipDialog(FragmentManager manager,String s,String rightString, View.OnClickListener rightClick) {
        if(tipDialog==null){
            tipDialog=new TipDialog();
        }
        tipDialog.setTitle(s)
                .setRightButton(rightString,rightClick)
                .show(this,manager);
    }

    private void showAsk(FragmentManager manager,String title, String leftString, View.OnClickListener leftClick, String rightString, View.OnClickListener rightClick){
        if(askDialog==null){
            askDialog =new AskDialog();
        }
        askDialog.setTitle(title)
                .setLeftButton(leftString,leftClick)
                .setRightButton(rightString,rightClick)
                .show(this,manager);
    }

    public void toast(String text){
        if(toast==null){
            //传入普通context，文字飘到别处，原因未知
            toast= Toast.makeText(getApplicationContext(),"",Toast.LENGTH_SHORT);
        }
        toast.setText(text);
        toast.show();
    }

    private void dismissTip() {
        if(tipDialog!=null){
            tipDialog.dismiss();
        }
    }

    public void dismissAsk() {
        if(askDialog!=null){
            askDialog.dismiss();
        }
    }

    public void showLoading() {
        progressLoading.setVisibility(View.VISIBLE);
    }

    public void dismissLoading() {
        progressLoading.setVisibility(View.GONE);
    }

    /*************************************MVP*******************************************/
    /**
     * 开始请求，显示加载动画
     */
    @Override
    public void onStartRequest() {
        showLoading();
    }

    /**
     * 完成请求，onResponse情况 取消加载动画
     */
    @Override
    public void onResponse() {
        dismissLoading();
    }

    /**
     * 完成请求，onFailure情况 取消加载动画
     */
    @Override
    public void onFailure(String str) {
        dismissLoading();
        toast(str);
    }

    @Override
    public void onData(List data) {
        if(data.isEmpty()){
            layoutEmpty.setVisibility(View.VISIBLE);
        }else {
            layoutEmpty.setVisibility(View.GONE);
        }
    }

    /**
     * 完成请求，message code success 取消加载动画
     */
    @Override
    public void onSuccess(String str) {

    }

    /**
     * 完成请求，message code error 提示信息
     */
    @Override
    public void onFail(String str) {
        toast(str);
    }

    /********************************Fragment**************************************/
    public void replaceFragment(int layout, Fragment fragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(layout, fragment)
                .commitAllowingStateLoss();
    }

    public void removeFragment(Fragment fragment) {
        getSupportFragmentManager()
                .beginTransaction()
                .remove(fragment)
                .commitAllowingStateLoss();
    }

    public void addFragment(Fragment fragment){
        getSupportFragmentManager()
                .beginTransaction()
                .add(fragment,"")
                .addToBackStack("")
                .commitAllowingStateLoss();
    }
}
